﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CROSLAND.BL.BE;
using System.Data.Common;
using System.Data;

namespace CROSLAND.DL.DALC.MSSQL
{
    public class StockDALC : BaseDALC, IStockDALC
    {        

        #region IStockDALC Members

        public List<StockBE> buscarStock(StockBE pObjStock)
        {
            //IRfcFunction function = null; RfcDestination dest = null;
            ////InMemoryDestinationConfiguration dc = new InMemoryDestinationConfiguration();

            //StockBE obj = null;
            //List<StockBE> listaResult = new List<StockBE>();
            //string ex_result = "";

            //try
            //{
            //    //try
            //    //{
            //    //    RfcDestinationManager.RegisterDestinationConfiguration(dc);
            //    //}
            //    //catch { }
            //    //RfcDestination dest = RfcDestinationManager.GetDestination(this._connId);
            //    dest = DALC.getDestination();
            //    function = dest.Repository.CreateFunction("ZWEB_BUSCA_STOCK");
            //    function.SetValue("P_MATNR", pObjStock.CodMaterial);
            //    function.SetValue("P_WERKS", pObjStock.CodCentro);
            //    function.SetValue("P_LGORT", pObjStock.CodAlmacen);
            //    function.SetValue("P_CHARG", pObjStock.CodLote);
            //    function.SetValue("P_PRDHA", pObjStock.Jerarquia);
            //    function.SetValue("P_VKORG", pObjStock.OrgVentas);
            //    function.SetValue("P_VTWEG", pObjStock.CanalDist);

            //    function.Invoke(dest);

            //    IRfcTable STOCK = function.GetTable("T_STOCK");

            //    foreach (IRfcStructure item in STOCK)
            //    {
            //        obj = new StockBE();

            //        obj.CodMaterial = item["MATNR"].ToString();
            //        obj.DescMaterial = item["MATNOM"].ToString();
            //        obj.CodCentro = item["WERKS"].ToString();
            //        obj.DescCentro = item["WERNOM"].ToString();
            //        obj.CodAlmacen = item["LGORT"].ToString();
            //        obj.DescAlmacen = item["LGONOM"].ToString();
            //        obj.CodLote = item["CHARG"].ToString();
            //        obj.StockDisponible = Convert.ToDecimal(item["STOCK_DI"].ToString());
            //        obj.StockEnTransito = Convert.ToDecimal(item["STOCK_CU"].ToString());
            //        obj.StockEntregaCliente = Convert.ToDecimal(item["STOCK_EC"].ToString());
            //        obj.StockLibre = Convert.ToDecimal(item["STOCK_LU"].ToString());
            //        obj.StockPedidoCliente = Convert.ToDecimal(item["STOCK_PC"].ToString());

            //        listaResult.Add(obj);
            //    }
            //}
            //catch (Exception ex)
            //{
            //    throw ex;
            //}
            //finally
            //{
            //    //RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            //}
            //return listaResult;
            return null;
        }

        public List<StockBE> buscarStockEC(StockBE pObjStock)
        {
            //IRfcFunction function = null; RfcDestination dest = null;
            ////InMemoryDestinationConfiguration dc = new InMemoryDestinationConfiguration();

            //StockBE obj = null;
            //List<StockBE> listaResult = new List<StockBE>();

            //try
            //{
            //    //try
            //    //{
            //    //    RfcDestinationManager.RegisterDestinationConfiguration(dc);
            //    //}
            //    //catch { }
            //    //RfcDestination dest = RfcDestinationManager.GetDestination(this._connId);
            //    dest = DALC.getDestination();
            //    function = dest.Repository.CreateFunction("ZWEB_BUSCA_STOCK_EC");
            //    function.SetValue("P_MATNR", pObjStock.CodMaterial);
            //    function.SetValue("P_WERKS", pObjStock.CodCentro);
            //    function.SetValue("P_LGORT", pObjStock.CodAlmacen);
            //    function.SetValue("P_CHARG", pObjStock.CodLote);
            //    function.SetValue("P_PRDHA", pObjStock.Jerarquia);

            //    function.Invoke(dest);

            //    IRfcTable STOCK = function.GetTable("T_STOCK_EC");

            //    foreach (IRfcStructure item in STOCK)
            //    {
            //        obj = new StockBE();

            //        obj.CodMaterial = item["MATNR"].GetString();
            //        obj.DescMaterial = item["MAKTX"].GetString();
            //        obj.CodCentro = item["WERKS"].GetString();
            //        obj.DescCentro = item["NAME1"].GetString();
            //        obj.CodAlmacen = item["LGORT"].GetString();
            //        obj.DescAlmacen = item["LGOBE"].GetString();
            //        obj.CodLote = item["CHARG"].GetString();
            //        obj.StockDisponible = Convert.ToDecimal(item["CDISP"].GetString());
            //        obj.StockEnTransito = Convert.ToDecimal(item["MENGE"].GetString());
            //        if (item["EINDT"].GetString() != "" && item["EINDT"].GetString() != "00000000")
            //        {
            //            obj.FechaStock = Convert.ToDateTime(item["EINDT"].GetString());
            //        }
            //        obj.UMB = item["MEINS"].GetString();

            //        listaResult.Add(obj);
            //    }
            //}
            //catch (Exception ex)
            //{
            //    throw ex;
            //}
            //finally
            //{
            //    //RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            //}
            //return listaResult;
            return null;
        }

        #endregion


        public List<ReservaBE> buscarStockVMS(string pCodMaterial, string pColor, string pCentro, string pAlmacen, string pLote,
                 string pJerarquia, string pGrart, string pAñoFab, string pDisponibilidad)
        {
            List<ReservaBE> entitys = new List<ReservaBE>();


            if (string.IsNullOrEmpty(pCodMaterial)) pCodMaterial = null;
            if (string.IsNullOrEmpty(pColor)) pColor = null;
            if (string.IsNullOrEmpty(pCentro)) pCentro = null;
            if (string.IsNullOrEmpty(pAlmacen)) pAlmacen = null;
            if (string.IsNullOrEmpty(pLote)) pLote = null;
            if (string.IsNullOrEmpty(pJerarquia) || pJerarquia == "0") pJerarquia = null;
            if (string.IsNullOrEmpty(pGrart)) pGrart = null;
            if (string.IsNullOrEmpty(pAñoFab)) pAñoFab = null;
            if (string.IsNullOrEmpty(pDisponibilidad)) pDisponibilidad = null;


            DbCommand command = dbProvider.GetStoredProcCommand("USPR_BUSQUEDA_VEHICULO");

            dbProvider.AddInParameter(command, "P_MATNR", DbType.String, string.IsNullOrEmpty( pCodMaterial )  ? "":pCodMaterial );
            dbProvider.AddInParameter(command, "P_COLOR", DbType.String, string.IsNullOrEmpty( pColor)  ? "": pColor);
            dbProvider.AddInParameter(command, "P_WERKS", DbType.String, string.IsNullOrEmpty( pCentro)  ? "":pCentro);
            dbProvider.AddInParameter(command, "P_LGORT", DbType.String, string.IsNullOrEmpty( pAlmacen)  ? "":pAlmacen);
            dbProvider.AddInParameter(command, "P_CHARG", DbType.String, string.IsNullOrEmpty( pLote)  ? "":pLote);
            dbProvider.AddInParameter(command, "P_JERARQUIA", DbType.String, string.IsNullOrEmpty( pJerarquia)  ? "":pJerarquia);
            dbProvider.AddInParameter(command, "P_MATKL", DbType.String, string.IsNullOrEmpty( pGrart)  ? "":pGrart);
            dbProvider.AddInParameter(command, "P_ANOFAB", DbType.String, string.IsNullOrEmpty( pAñoFab)  ? "":pAñoFab);
            dbProvider.AddInParameter(command, "P_AVAIL", DbType.String, string.IsNullOrEmpty(pDisponibilidad) ? "" : pDisponibilidad);

            ReservaBE entity = new ReservaBE();
            string msg = string.Empty;
            using (IDataReader dr = dbProvider.ExecuteReader(command))
            {
                while (dr.Read())
                {
                    try
                    {
                        entity = new ReservaBE();
                        msg = dr["ZLOTE"].ToString();
                        entity.codMaterial = dr["ZMATERIAL"].ToString();
                        entity.descMaterial = dr["ZDESC_MATERIAL"].ToString();
                        entity.lote = dr["ZLOTE"].ToString();
                        entity.añoFab = dr["ZANO_FAB"].ToString();
                        entity.añoModelo = dr["ZANO_MODELO"].ToString();
                        entity.campaña = dr["ZCAMPANA"].ToString();
                        entity.color = dr["ZCOLOR"].ToString();
                        entity.descColor = dr["ZDESC_COLOR"].ToString();
                        entity.descCentro = dr["ZDESC_CENTRO"].ToString();
                        entity.descAlmacen = dr["ZDESC_ALMACEN"].ToString();
                        entity.cantidad = Convert.ToDecimal(dr["ZCANTIDAD"].ToString());
                        entity.disponibilidad = dr["ZDISPONIBILIDAD"].ToString();
                        entity.descCliente = dr["ZDESC_SOLIC"].ToString();

                        if (dr["ZFEC_VENC"].ToString() == "00000000")
                        {
                            entity.fecVencimiento = null;
                        }
                        else
                        {
                            if (!dr["ZFEC_VENC"].Equals(""))
                            {
                                entity.fecVencimiento = Convert.ToDateTime( dr["ZFEC_VENC"]);
                            }
                        }
                        if (dr["ZFEC_NAC_REAL"].ToString() == "00000000")
                        {
                            entity.fecNacionalizacion = null;
                        }
                        else
                        {
                            if (!dr["ZFEC_NAC_REAL"].Equals(""))
                            {
                                entity.fecNacionalizacion = Convert.ToDateTime(dr["ZFEC_NAC_REAL"]);
                            }
                        }
                        entity.emplazamiento = dr["ZEMPLAZAMIENTO"].ToString();
                        entity.status = dr["ZSTATUS"].ToString();
                        entity.chasis = dr["ZCHASIS"].ToString();
                        entity.motor = dr["ZMOTOR"].ToString();
                        if (!dr["ZCAJA"].ToString().Equals(""))
                        {
                            entity.caja = Convert.ToDecimal(dr["ZCAJA"].ToString());
                        }
                        entity.pedidoImportacion = dr["ZPEDIDOIMP"].ToString();
                        entity.marca = dr["ZMARCA"].ToString();
                        entity.modelo = dr["ZMODELO"].ToString();
                        entity.grupoArticulo = dr["ZGRUPO_ARTICULO"].ToString();

                        entitys.Add(entity);
                    }
                    catch (Exception ex)
                    {
                        Console.Write(msg);
                    }
                }
            }


            return entitys;
        }

        public List<string> GenerarReserva(DateTime fechaInicio, DateTime fechaFin, string orgVtas, string canal, string codCliente, 
            string oficina, List<string> lstLote, List<GenericBE> lstStatus)
        {
            List<string> resultado = new List<string>();

            DbCommand command = dbProvider.GetStoredProcCommand("USPC_RESERVA_STOCK");

            foreach (string lote in lstLote)
            {
                command.Parameters.Clear();

                dbProvider.AddInParameter(command, "FECHAI", DbType.DateTime, fechaInicio);
                dbProvider.AddInParameter(command, "FECHAF", DbType.DateTime, fechaFin);
                dbProvider.AddInParameter(command, "VKORG", DbType.String, orgVtas);
                dbProvider.AddInParameter(command, "VTWEG", DbType.String, canal);
                dbProvider.AddInParameter(command, "VKBUR", DbType.String, oficina);
                dbProvider.AddInParameter(command, "KUNNR", DbType.String, codCliente);
                dbProvider.AddInParameter(command, "VHCLE", DbType.String, lote);
                dbProvider.AddOutParameter(command, "VGUID", DbType.String, 22);

                int result = Convert.ToInt32(dbProvider.ExecuteScalar(command));
                string codVehiculo = dbProvider.GetParameterValue(command, "VGUID").ToString();
                string msg = string.Empty;
                if (result == 1) msg = "Reserva Ok";
                if (result == 0) msg = "Ya existe reserva";
                if (result == -1) msg = "Error al reservar";

                resultado.Add("Lote: " + lote + " Resultado: " + msg);
            }

            return resultado;
                       
        }

        public List<string> AsignarCampana(List<string> lstLote, List<GenericBE> lstStatus, string pCamp, UsuarioWebBE uw)
        {
            //List<string> resultado = new List<string>();

            //DbCommand command = dbProvider.GetStoredProcCommand("USPU_ASIGNA_CAMPANIA");

            //foreach (string lote in lstLote)
            //{
            //    command.Parameters.Clear();

            //    dbProvider.AddInParameter(command, "VHCLE", DbType.String, lote);
            //    dbProvider.AddInParameter(command, "CMPGN", DbType.String, pCamp);
            //    dbProvider.AddOutParameter(command, "VGUID", DbType.String, 22);


            //    int result = Convert.ToInt32(dbProvider.ExecuteScalar(command));
            //    string codVehiculo = dbProvider.GetParameterValue(command, "VGUID").ToString();
            //    string msg = string.Empty;
            //    if (result == 0) msg = "Asignación Ok";                
            //    if (result == -1) msg = "Error al asignar la campaña";

            //    resultado.Add("Lote: " + lote + " Resultado: " + msg);

            //}

            //return resultado;

            throw new NotImplementedException();
        }
    }
}
